<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<div id="page-content">
    <div class="row"> 

        <div class="col-lg-12">
            <div class="panel">
                <div class="panel-heading">
                    <h3 class="panel-title">部门管理</h3>
                </div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-md-3">
                            <ul id="tree_department" class="ztree"></ul>
                        </div>
                        <div class="col-md-9">
                            <div class="form-inline">
                                <div class="row">
                                    <div class="col-sm-12 table-toolbar-left">
                                        <%--
                                        <btn id="btn_add_duty" class="btn btn-primary btn-sm">
                                            <i class="ti-plus"> </i> 添加成员
                                        </btn>
                                        --%>
                                    </div>
                                </div>
                            </div>
                            <div class="jqGrid_wrapper">
                                <table id="duty_table"></table>
                                <div id="duty_page"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script>

    $(function(){

        init_tree_department();

    });

    function init_tree_department() {

        var setting = {
            async: {
                enable: true,
                url:'<%=path%>/main/department/tree',
                autoParam: ['id'],
                type: 'get',
                dataType: 'json'
            },
            callback: {
                onAsyncSuccess: zTreeOnAsyncSuccess,
                beforeEditName: zTreeBeforeEditName,
                beforeRemove: zTreeBeforeRemove,
                onClick: zTreeOnClick,
                onCheck: zTreeOnCheck
            },
//            check: {
//                enable: true,
//                chkStyle: 'checkbox',
//                chkboxType:  { 'Y' : '', 'N' : '' }
//            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'pId',
                    rootPId: ''
                }
            },
            edit: {
                enable: true,
                removeTitle: '删除',
                renameTitle: '编辑',
                showRemoveBtn: setRemoveBtn,
                showRenameBtn: setRenameBtn
            },
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                autoCancelSelected: false,
                dblClickExpand: false,
                selectedMulti: false
            }
        };

        $.fn.zTree.init($('#tree_department'), setting);

    }
    
    function addHoverDom(treeId, treeNode) {
        var sObj = $('#' + treeNode.tId + '_span');
        if (treeNode.editNameFlag || $('#addBtn_'+treeNode.id).length>0) return;
        var addStr = '<span class="button add" id="addBtn_' + treeNode.id + '" title="新增" onfocus="this.blur();"></span>';
        sObj.after(addStr);
        var btn = $('#addBtn_'+treeNode.id);
        if (btn) btn.bind('click', function(){
            add_department(treeNode.id);
            return false;
        });
    }

    function removeHoverDom(treeId, treeNode) {
        $('#addBtn_'+treeNode.id).unbind().remove();
    }

    function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
        var zTree = $.fn.zTree.getZTreeObj('tree_department');
        if (treeNode) {
            if (treeNode.id === '0') {
                var nodes = treeNode.children;
                zTree.selectNode(nodes[0]);
                init_grid_duty(nodes[0].id);
            }
        } else {
            var rootNode = zTree.getNodes()[0];
            if (rootNode.isParent) {
                zTree.expandNode(rootNode, true, true, true);
            }
        }
    }

    function setRenameBtn(treeId, treeNode) {
        return (treeNode.id !== '0');
    }

    function zTreeBeforeEditName(treeId, treeNode) {
        edit_department(treeNode.id);
        return false;
    }

    function setRemoveBtn(treeId, treeNode) {
        return (treeNode.id !== '0');
    }

    function zTreeBeforeRemove(treeId, treeNode) {
        delete_department(treeNode.id);
        return false;
    }

    function zTreeOnClick(event, treeId, treeNode){
        var id = treeNode.id;
        if (id && id != "0") {
            $('#duty_table').jqGrid().setGridParam({datatype:'json',postData: {departmentId: id}, page: 1}).trigger('reloadGrid');
        }
    }

    function zTreeOnCheck(event, treeId, treeNode){

    }

    $('#btn_add_department').click(function() {
        add_department();
        return false;
    });

    $('#btn_add_child_department').click(function() {
        var zTree = $.fn.zTree.getZTreeObj('tree_department');
        var selectedNodes = zTree.getSelectedNodes();
        if (selectedNodes.length > 0) {
            add_department(selectedNodes[0].id);
        } else {
            __toastr_warning('请选择一个部门');
        }
        return false;
    });

    function add_department(departmentId) {
        var url = '<%=path%>/main/department/create';
        if (departmentId) {
            url = '<%=path%>/main/department/create?departmentId=' + departmentId;
        }
        __open_dialog_form('新增部门', url, function (dialogRef) {
            var callback = function (data) {
                if (data) {
                    dialogRef.close();

                    // 刷新tree
                    refresh_department(data.parentId);
                } else {
                    dialogRef.enableButtons();
                }
            };
            if (fn_department_input_save(callback) === false) {
                dialogRef.enableButtons();
            }
        });
    }

    function edit_department(departmentId) {
        if (departmentId) {
            var url = '<%=path%>/main/department/update/'+departmentId;
            __open_dialog_form('编辑部门信息', url, function (dialogRef) {
                var callback = function (data) {
                    if (data) {
                        dialogRef.close();

                        // 刷新tree
                        refresh_department(data.parentId);
                    } else {
                        dialogRef.enableButtons();
                    }
                };
                if (fn_department_input_save(callback) === false) {
                    dialogRef.enableButtons();
                }
            });
        } else {
            __toastr_warning('请选择一个部门');
        }
    }

    function delete_department(departmentId) {
        if (departmentId) {
            fn_depart_delete(departmentId);
        } else {
            __toastr_warning('请选择一个部门');
        }
    }

    function refresh_department(departmentId) {
        var zTree = $.fn.zTree.getZTreeObj('tree_department');
        if (departmentId) {
            var node = zTree.getNodeByParam('id', departmentId, null);
            // parentNode.isParent = false 时，不进行异步加载
            if (!node.isParent) {
                node.isParent = true;
                zTree.updateNode(node);
            }
            zTree.reAsyncChildNodes(node, 'refresh');
        } else {
            zTree.reAsyncChildNodes(null, 'refresh');
        }
    }

    function init_grid_duty(departmentId) {

        __init_jqgrid('duty_table', 'duty_page',
                '<%=path%>/main/duty/list_department',
                ['成员', '岗位名称', '身份', '操作', 'id'],
                [
                    {name: 'userName', index: 'userName', width: 60, sortable: true, stype: 'text', searchoptions: {sopt: ['cn']}},
                    {name: 'postName', index: 'postName', width: 60, sortable: true, stype: 'text', searchoptions: {sopt: ['cn']}},
                    {name: 'dutyState', index: 'dutyState', width: 60, sortable: true, stype: 'text', searchoptions: {sopt: ['cn']}},
                    {name: 'act', index: 'act', width: 230, fixed: true, sortable: false, search: false, formatter: actFormat},
                    {name: 'id', index: 'id', width: 100, key: true, hidden: true, hidedlg: true}
                ],
                true,
                {
                    postData: {departmentId: departmentId}
                }
        );

    }

    function actFormat(cellvalue, options, rowObject){
        var id = rowObject.id;
        var departId = rowObject.departmentId;
        var dutyState = rowObject.dutyState;
        var dutyTitle ="设为部门负责人";
        if(dutyState == "负责人"){
            dutyTitle = "设为组员";
        }
        cellvalue = '<button class="btn btn-warning btn-xs" data-original-title="'+dutyTitle+'" onclick="fn_depart_lead(\'' + id + '\', \'' +departId + '\');"><i class="fa fa-pencil-square-o"> </i> '+dutyTitle+'</button> ';
       // cellvalue += '<button class="btn btn-danger btn-xs" data-original-title="删除" onclick="fn_depart_delete(\'' + id + '\');"><i class="fa fa-trash-o"> </i> 删除</button>';

        return cellvalue;
    }
    /*
    $('#btn_add_duty').click(function() {
        var zTree = $.fn.zTree.getZTreeObj('tree_department');
        var selectedNodes = zTree.getSelectedNodes();
        if (selectedNodes.length > 0) {
            // 部门 Id
            var departmentId = selectedNodes[0].id;
            // 弹出表单
            __open_dialog_form('添加成员', '<%=path%>/main/duty/create?departmentId='+departmentId, function (dialogRef) {
                var callback = function (data) {
                    if (data) {
                        dialogRef.close();

                        //刷新grid
                        $('#duty_table').trigger('reloadGrid');
                    } else {
                        dialogRef.enableButtons();
                    }
                };
                if (fn_duty_input_save(callback) === false) {
                    dialogRef.enableButtons();
                }
            });
        } else {
            __toastr_warning('请选择一个部门');
        }
    });

    function fn_duty_edit(id) {
        __open_dialog_form('添加成员', '<%=path%>/main/duty/update/'+id, function (dialogRef) {
            var callback = function (data) {
                if (data) {
                    dialogRef.close();

                    //刷新grid
                    $('#duty_table').trigger('reloadGrid');
                } else {
                    dialogRef.enableButtons();
                }
            };
            if (fn_duty_input_save(callback) === false) {
                dialogRef.enableButtons();
            }
        });
    }*/

    function fn_depart_lead(rowId, keyId){
        var actionUrl = "<%=path%>/main/department/lead";
        var data={rowId:rowId,keyId:keyId};
        __ajax_post(actionUrl, data, function(pdata) {
            __toastr_success(pdata.message);
            $("#duty_table").jqGrid().setGridParam({datatype:'json'}).trigger("reloadGrid");
        });
    }
    //删除部门
    function fn_depart_delete(keyId){
        var actionUrl = "<%=path%>/main/department/delete";
        var data={keyId:keyId};
        __ajax_post(actionUrl, data, function(pdata) {
            __toastr_success(pdata.message);
            refresh_department(0);
          
        });
    }
    function fn_duty_method(method, id) {
        <%--var message = '确定执行此操作么';--%>
        <%--if (method == 'Delete') {--%>
            <%--message = '确定删除么';--%>
        <%--} else if (method == 'Enable') {--%>
            <%--message = '确定启用么';--%>
        <%--} else if (method == 'Disenable') {--%>
            <%--message = '确定禁用么';--%>
        <%--}--%>
        <%--var callback = {--%>
            <%--confirm:function(){--%>
                <%--var url = '<%=path%>/main/post/method/'+method+'/'+id;--%>
                <%--__ajax_post(url, null, null, function(data) {--%>
                    <%--__toastr(data);--%>
                    <%--if(data.state == 1) {--%>
                        <%--// 刷新grid--%>
                        <%--$('#post_table').trigger('reloadGrid');--%>
                    <%--}--%>
                <%--});--%>
                <%--swal.close();--%>
            <%--}--%>
        <%--};--%>
        <%--__confirm(message, null, callback);--%>
    }

</script>